package com.itheima.app.manager;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.itheima.app.controller.MovementController;
import com.itheima.app.interceptor.UserHolder;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.mongo.Comment;
import com.itheima.domain.mongo.FocusUser;
import com.itheima.domain.mongo.Video;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.mongo.CommentService;
import com.itheima.service.mongo.FocusUserService;
import com.itheima.service.mongo.VideoService;
import com.itheima.util.ConstantUtil;
import com.itheima.vo.CommentVo;
import com.itheima.vo.PageBeanVo;
import com.itheima.vo.VideoVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
public class VideoManager {

    @DubboReference
    VideoService videoService;

    @DubboReference
    UserInfoService userInfoService;

    @Autowired
    FastFileStorageClient client;

    @Autowired
    FdfsWebServer server;

    @DubboReference
    FocusUserService focusUserService;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired
    MovementManager movementManager;

    @DubboReference
    CommentService commentService;

    @Autowired
    MQMovementManager mqMovementManager;

    /*
        value:名称空间
        key:缓存中的key   用户id_页码_每页条数
        unless:当查询的页面中的数据为空的时候就不缓存
     */
    @Cacheable(value = "tanhua",key = "#userId+'_'+#pageNum+'_'+#pageSize",unless = "#result.counts==0" )
    public PageBeanVo findRecommendVideoByPage(Long userId, Integer pageNum, Integer pageSize) {
//        //1.获取登陆者id
//        //2.调用service获取PageBeanVo
//        PageBeanVo pageBeanVo = videoService.findRecommendVideoByPage(userId, pageNum, pageSize);
//
//        //3.从pageBeanVo中获取视频列表
//        List<Video> items = (List<Video>) pageBeanVo.getItems();
//
//        //4.遍历视频列表,获取每个视频的发布人id,查询其userInfo,将视频和userInfo封装videoVo对象,将每个vo对方放入预先声明好的voList中
//        List<VideoVo> voList = new ArrayList<>();
//        if (CollUtil.isNotEmpty(items)) {
//            items.forEach(video -> {
//                Long videoUserId = video.getVid();
//                UserInfo userInfo = userInfoService.findById(videoUserId);
//
//                VideoVo vo = new VideoVo();
//                //注意:先封装userInfo,后封装video,最终vo中的id为视频id
//                vo.setUserInfo(userInfo);
//                vo.setVideo(video);
//
//                //判断用户是否关注过
//                if (stringRedisTemplate.hasKey(StrUtil.format(ConstantUtil.FOCUS_USER,userId,video.getId()))) {
//                    vo.setHasFocus(1);
//                }
//                //判断用户是点赞过
//                if (stringRedisTemplate.hasKey(StrUtil.format(ConstantUtil.VIDEO_LIKE,userId,video.getId()))) {
//                    vo.setHasLiked(1);
//                }
//                voList.add(vo);
//            });
//        }
//
//        //5.将voList设置给pageBeanVo
//        pageBeanVo.setItems(voList);
//
//        //6.返回pageBeanVo即可
//        return pageBeanVo;


        //1.远程调用videoservice查询数据
        PageBeanVo pageBeanVo = videoService.findRecommendVideoByPage(userId, pageNum, pageSize);

        //2.获取分页数据中videoList,遍历集合,获取每个video,获取发布者id,获取发布者userInfo
        List<VideoVo> voList = new ArrayList<>();

        List<Video> items = (List<Video>) pageBeanVo.getItems();
        if (CollUtil.isNotEmpty(items)) {
            for (Video video : items) {
                //获取发布者id,获取发布者userInfo
                UserInfo userInfo = userInfoService.findById(video.getUserId());

                //3.将每个video和userInfo封装videoVo,将每个vo放入voList中
                VideoVo vo = new VideoVo();

                //先封装userInfo,再封装video
                vo.setUserInfo(userInfo);
                vo.setVideo(video);

                //判断用户是点赞过
                if (stringRedisTemplate.hasKey(StrUtil.format(ConstantUtil.VIDEO_LIKE,userId,video.getId()))) {
                    vo.setHasLiked(1);
                }
                voList.add(vo);
            }
        }
        //4.将voList设置给pageBeanVo且返回
        pageBeanVo.setItems(voList);
        return pageBeanVo;
    }

    @CacheEvict(value = "tanhua",allEntries = true)
    //加上笔记中的三个类之后就可以使用通配符删除指定用户的缓存了
//    @CacheEvict(value = "tanhua",key = "#userId+'_*'")
    public void save(Long userId, MultipartFile videoThumbnail, MultipartFile videoFile) throws IOException {
        //1.上传俩文件到fdfs上,获取俩路径
        StorePath coverPath = client.uploadFile(videoThumbnail.getInputStream(), videoThumbnail.getSize(),
                FileUtil.extName(videoThumbnail.getOriginalFilename()), null);
        StorePath videoPath = client.uploadFile(videoFile.getInputStream(), videoFile.getSize(),
                FileUtil.extName(videoFile.getOriginalFilename()), null);

        //2.封装video(userId,图片路径,视频路径...)
        Video video = new Video();
        video.setCreated(System.currentTimeMillis());
        video.setUserId(userId);
        video.setText("犯我中华者,虽远必诛!");
        video.setPicUrl(server.getWebServerUrl()+coverPath.getFullPath());
        video.setVideoUrl(server.getWebServerUrl()+videoPath.getFullPath());

        System.out.println(video.getVideoUrl());
        System.out.println(video.getPicUrl());

        //3.调用service完成保存操作
        videoService.save(video);
    }

    @CacheEvict(value = "tanhua",allEntries = true)
    //加上笔记中的三个类之后就可以使用通配符删除指定用户的缓存了
//    @CacheEvict(value = "tanhua",key = "#userId+'_*'")
    public void focusUser(Long userId, Long focusUserId) {
        //1.封装focusUser
        FocusUser focusUser = new FocusUser();
        focusUser.setUserId(userId);
        focusUser.setFocusUserId(focusUserId);
        focusUser.setCreated(System.currentTimeMillis());

        //2.调用service完成保存操作
        focusUserService.save(focusUser);

        //3.往redis中保存关注的标识
        stringRedisTemplate.opsForValue().set(StrUtil.format(ConstantUtil.FOCUS_USER,userId,focusUserId),"1");
    }

    @CacheEvict(value = "tanhua",allEntries = true)
    //加上笔记中的三个类之后就可以使用通配符删除指定用户的缓存了
//    @CacheEvict(value = "tanhua",key = "#userId+'_*'")
    public void unFocusUser(Long userId, Long focusUserId) {
        //1.调用service完成删除操作
        focusUserService.delete(userId,focusUserId);
        //2.从redis中删除关注的标识
        stringRedisTemplate.delete(StrUtil.format(ConstantUtil.FOCUS_USER,userId,focusUserId));
    }

//    @CacheEvict(value = "tanhua",key = "#id+'_*'")
    @CacheEvict(value = "tanhua",allEntries = true)
    public ResponseEntity likeVideo(String id) {
        Long userId = UserHolder.get().getId();
        Video video = videoService.findById(id);

        Comment comment = new Comment();
        comment.setCreated(System.currentTimeMillis());
        comment.setPublishId(new ObjectId(id));
        comment.setCommentType(4);
        comment.setUserId(userId);
        comment.setPublishUserId(video.getUserId());

        int count = commentService.save(comment);
        stringRedisTemplate.opsForValue().set(StrUtil.format(ConstantUtil.VIDEO_LIKE,userId,id),"1");

        return ResponseEntity.ok(count);
    }

//    @CacheEvict(value = "tanhua",key = "#id+'_*'")
    @CacheEvict(value = "tanhua",allEntries = true)
    public ResponseEntity dislikeVideo(String id) {
        Long userId = UserHolder.get().getId();
        int count = commentService.delete(userId, new ObjectId(id), 4);
        stringRedisTemplate.delete(StrUtil.format(ConstantUtil.VIDEO_LIKE,userId,id));
        return ResponseEntity.ok(count);
    }

    @CacheEvict(value = "tanhua",allEntries = true)
//    @CacheEvict(value = "tanhua",key = "#id+'_*'")
    public ResponseEntity queryCommentsList(String id, Integer page, Integer pagesize) {
        Long userId = UserHolder.get().getId();
        PageBeanVo pageBeanVo = commentService.queryCommentsList(new ObjectId(id), page, pagesize);
        List<Comment> items = (List<Comment>) pageBeanVo.getItems();
        List<CommentVo> voList=new ArrayList<>();

        if (CollUtil.isNotEmpty(items)){
            for (Comment item : items) {
                UserInfo userInfo= userInfoService.findById(item.getUserId());
                CommentVo vo=new CommentVo();
                vo.setId(item.getId().toString());
                vo.setAvatar(userInfo.getAvatar());
                vo.setNickname(userInfo.getNickname());
                vo.setContent(item.getContent());
                vo.setCreateDate(DateUtil.formatDateTime(new Date(item.getCreated())));
                vo.setLikeCount(item.getLikeCount());

                voList.add(vo);
            }
        }
        pageBeanVo.setItems(voList);
        return ResponseEntity.ok(pageBeanVo);
    }

//    @CacheEvict(value = "tanhua",key = "#id+'_*'")
    @CacheEvict(value = "tanhua",allEntries = true)
    public void saveComments(String id, String content) {
        Long userId = UserHolder.get().getId();
        Video video = videoService.findById(id);
        Comment comment = new Comment();
        comment.setCreated(System.currentTimeMillis());
        comment.setPublishId(video.getId());
        comment.setCommentType(5);
        comment.setUserId(userId);
        comment.setPublishUserId(video.getUserId());
        comment.setContent(content);
        commentService.save(comment);
    }
}
